package com.pdweb.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pdweb.dao.CargosDao;
import com.pdweb.vo.Cargos;

/**
 * Servlet implementation class CargosConsultaServlet
 */
@WebServlet("/CargosConsultaServlet")
public class CargosConsultaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CargosConsultaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);
		
	}
	
	protected void doService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {

			Cargos cargos = new Cargos();

			cargos.setNomeCargo(request.getParameter("nomeCargo"));
			
			String sql = null;
			CargosDao cargosDao = new CargosDao();
			String buscaNumeros = cargos.getNomeCargo();
			
			Pattern p = Pattern.compile("[0-9]{"+ buscaNumeros.length() +"}");   
			Matcher m = p.matcher(buscaNumeros);
			if (m.find()) {
				sql = "select * from cargos where id_cargo_carg = "+cargos.getNomeCargo()+";"; 
			} else {
				sql = "select * from cargos where st_nome_carg = '"+cargos.getNomeCargo()+"';"; 
			}
			
			List<Cargos> cargos1 = cargosDao.consultaCargo(sql);
			 
			 if( cargos1 != null){
				 
				 request.setAttribute("cargosConsulta", cargos1);
					
					getServletContext().getRequestDispatcher("/consulta_cargo.jsp").forward(request,response);
			 } else {
				 request.setAttribute("erro", "sem valores");
					
					getServletContext().getRequestDispatcher("/consulta_cargo.jsp").forward(request,response);
			 }
			
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
